package com.huisou.web;

import com.huisou.basedataservice.AreaDao;
import com.huisou.domain.Area;
import com.huisou.utils.WebUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CodeAction {
	
	@Resource
	private AreaDao	ad;
	
	@RequestMapping(value = "/arealist.htm", method = RequestMethod.GET)
	@ResponseBody
	public String cateList(HttpServletRequest req) {
		int pid = WebUtil.getInt(req, "pid");
		ObjectMapper m = new ObjectMapper();
		List<Area> la = ad.queryAreaListByPid(pid);
		String res = null;
		if (la != null && la.size() > 0) {
			List<Map> mylist = new ArrayList<Map>();
			for (Area area : la) {
				Map<String, Object> cm = new HashMap<String, Object>();
				cm.put("cid", area.getId());
				cm.put("name", area.getName());
				mylist.add(cm);
			}
			try {
				res = m.writeValueAsString(mylist);
			}
			catch (JsonGenerationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
	
	@RequestMapping(value = "/arealistpinyin.htm")
	@ResponseBody
	public String cateListPinyin(HttpServletRequest req) {
		int pid = WebUtil.getInt(req, "pid");
		ObjectMapper m = new ObjectMapper();
		List<Area> la = ad.queryAreaListByPidPinyin(pid);
		String res = null;
		if (la != null && la.size() > 0) {
			List<Map> mylist = new ArrayList<Map>();
			for (Area area : la) {
				Map<String, Object> cm = new HashMap<String, Object>();
				cm.put("cid", area.getId());
				cm.put("name", area.getName());
				mylist.add(cm);
			}
			try {
				res = m.writeValueAsString(mylist);
			}
			catch (JsonGenerationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return res;
	}
	
	@RequestMapping(value = "/getareaname.htm")
	@ResponseBody
	public String getAreaName(HttpServletRequest req) {
		int id = WebUtil.getInt(req, "id");		
		String res = ad.getAreaNameById(id);
		return "[\""+res+"\"]";
	}
}
